package com.kould.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.houbb.data.factory.core.util.DataUtil;
import com.kould.common.result.Result;
import com.kould.enity.Article;
import com.kould.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @GetMapping("/kache/{id}")
    public Result pageArticleForKache(@PathVariable("id") Long id) {
        return Result.success(articleService.findArticleByIdForKache(id));
    }

    @GetMapping("/spring/{id}")
    public Result pageArticleForSpring(@PathVariable("id") Long id) {
        return Result.success(articleService.findArticleByIdForSpring(id));
    }

    @GetMapping("/kache/title")
    public Result pageArticleForKache(Page<Article> page, String title) {
        return Result.success(articleService.findArticlesTitleLikeForKache(page, title));
    }

    @GetMapping("/spring/title")
    public Result pageArticleForSpring(Page<Article> page, String title) {
        return Result.success(articleService.findArticlesTitleLikeForSpring(page, title));
    }

    @GetMapping("/kache/page")
    public Result pageArticleForKache(Page<Article> page) {
        return Result.success(articleService.findArticlesForKache(page));
    }

    @GetMapping("/spring/page")
    public Result pageArticleForSpring(Page<Article> page) {
        return Result.success(articleService.findArticlesForSpring(page));
    }

    @DeleteMapping("/{id}")
    public Result deleteArticle(@PathVariable("id") Long id) {
        return Result.success(articleService.deleteArticleForKacheAndSpringById(id));
    }

    @PostMapping("/test/batch")
    public Result insertBatchArticle(Integer size, Integer time) {
        int result = 0;
        for (int i = 0; i < time; i++) {
            result += batchInsetRandomData(size);
        }
        return Result.success(result);
    }

    private Integer batchInsetRandomData(Integer size) {
        List<Article> list = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            Article build = DataUtil.build(Article.class);
            build.setId(null);
            build.setDeleted(0);
            list.add(build);
        }
        return articleService.insertBatchArticleForKacheAndSpring(list);
    }

}
